package server

import (
	"encoding/json"
	"errors"
	"github.com/nsqio/go-nsq"
	"server/base"
	"server/common/dao/group"
	message2 "server/common/models/message"
	"server/common/utils"
	"server/pkg/log"
	nsq2 "server/pkg/nsq"
	"server/pkg/websocket"
)

type GroupMessage struct {
}

func (g GroupMessage) GetTopic() string {
	return string(nsq2.TOPIC_GROUP_MESSAGE)
}

func (g GroupMessage) GetChannel() string {
	return string(nsq2.TOPIC_GROUP_MESSAGE)
}

func (u GroupMessage) GetHandler() func(message *nsq.Message) error {
	return func(message *nsq.Message) error {
		// 解析消息
		var userMessage message2.GroupMessage
		err := json.Unmarshal(message.Body, &userMessage)
		if err != nil {
			log.Error("[GroupMessage]", err, string(message.Body))
			return nil
		}

		// 创建消息
		base.Mysql.Create(&userMessage)
		if userMessage.Id == 0 {
			log.Error("[GroupMessage]", errors.New("消息发送失败"), string(message.Body))
		}

		// 获取群组用户列表
		userIds, err := group.GroupDao.GroupIdToUserIds(userMessage.GroupId)
		if err != nil {
			log.Error("[GroupMessage]", err, string(message.Body))
			return nil
		}

		// 发送消息循环推送
		for _, userId := range userIds {
			base.App.WebSocketHub.SendToUser(utils.UserIdToSocketId(userId), websocket.Message{
				Type: "group_message", Data: userMessage,
			})
		}
		return nil
	}
}
